<template>
	<div class="list">
		<!-- 工具条 -->
		<el-col :span="24" class="toolbar">
			<el-input placeholder="请输入内容" v-model="filters.name" class="search">
				<el-button slot="append" icon="el-icon-search" @click="getTableData"></el-button>
			</el-input>
		</el-col>
		<el-table :data="tableData" v-loading="listLoading" stripe>
			<el-table-column prop="requires_id" label="ID" width="50"></el-table-column>
			<el-table-column prop="o_id" label="订单号"></el-table-column>
			<el-table-column prop="product_name" label="作品名称"></el-table-column>
			<el-table-column prop="product_type_zh" label="分类"></el-table-column>
			<el-table-column label="操作" width="80">
				<template slot-scope="scope">
					<span class="hover" @click="handleAdd(scope.$index, scope.row)">录入</span>
				</template>
			</el-table-column>
		</el-table>
		<!-- 工具条 -->
		<el-col :span="24" class="toolbar" style="padding-top:10px;">
			<el-pagination layout="prev, pager, next" @current-change="handleCurrentChange" :page-size="10" :total="total" style="float:right;">
			</el-pagination>
		</el-col>
		<!-- 新增 -->
		<el-dialog title="盗版录入" :visible.sync="formAddVisible" width="700px">
			<el-form ref="formAdd" :model="formAdd" :rules="formAddRules" label-width="80px">
				<el-form-item label="网站名称" prop="site_name">
                    <el-input v-model="formAdd.site_name"></el-input>
				</el-form-item>
				<el-form-item label="网站网址" prop="url">
                    <el-input v-model="formAdd.url"></el-input>
				</el-form-item>
				<el-form-item label="内容名称" prop="unauth_name">
                    <el-input v-model="formAdd.unauth_name"></el-input>
				</el-form-item>
				<el-form-item label="网页截图" prop="pic" class="el-form-pic">
                    <el-upload
                    :action="uploadUrl"
                    list-type="picture-card"
                    :on-success="unauthSuccess"
                    :on-remove="unauthRemove"
                    :before-upload="unauthUpload"
                    :limit="1"
                    :on-exceed="unauthExceed"
                    :file-list="fileList.unauth">
                        <i class="el-icon-plus"></i>
                    </el-upload>
                    <div class="el-upload__tip">支持上传图片，每个文件小于2M，最多上传1个文件</div>
				</el-form-item>
				<el-form-item>
					<el-button type="primary" @click="submitAdd('formAdd')">提交</el-button>
					<el-button @click="formAddVisible = false">取消</el-button>
				</el-form-item>
			</el-form>
		</el-dialog>
	</div>
</template>

<script>
	import { mapState,mapMutations } from 'vuex'
	import { getunauthrequires,unauthAdd,unauthCheckurl,submitfile } from '@/api';

	export default {
		data() {
			var validateUrl = (rule, value, callback) => {
				if (value === '') {
					callback(new Error('请输入盗版网站网址'));
				} else {
					let domainArr = value.match(/[\w-]+\.(com|net|org|gov|cc|biz|info|cn|co|mobi|name|sh|ac|la|travel|tm|us|cc|tv|jobs|asia|hn|lc|hk|bz|ws|tel|io|tw|is|edu|mil|au|jp|int|kr|de|vc|ag|in|me|gd|vg|be|sg|it|ro|pw|win|cm|im|ca|top|wang|tt|so|xyz|vip|tn)\b(\.(cn|hk|uk|jp|tw|kr|mo|kr|ru))*/);
					// 2017-11-14 18:00:31 liuzz
					if(!domainArr){
						let urlReg = /[a-zA-Z0-9][-a-zA-Z0-9]{0,62}(\.[a-zA-Z0-9][-a-zA-Z0-9]{0,62})+\.?/;  
						let urlIP=urlReg.exec(value);
						if(urlIP){
							if(this.isIp(urlIP[0])){
								domainArr = true;
							}
						}
					}
					if(!this.IsURL(value) || !domainArr){
						callback(new Error('此网址不是以http://https://开头，或者不是网址'));
					}else{
						let para= {
							uid: this.crocUser.uid,
							requires_id: this.requires_id,
							// unauth_id: this.unauth_id,
							url: value,
						}
						unauthCheckurl(para).then(res=> {
							if(res.data){
								callback();
							}else{
								callback(new Error('此盗版网址已经录入了'));
							}
						});
					}
				}
			};
			return {
				// 翻页
				total: 0,
				page: 1,
				listLoading: false,

				filters: {
					name: '',
				},

				// 表格
				tableData: [],
				// 添加弹出框
				formAddVisible: false,
				formAdd: {
					site_name: '',
					url: '',
					unauth_name: '',
					pic: '',
				},
				formAddRules: {
					site_name: [{ required: true, message: "请填写盗版网站名称" }],
					url: [
						{ required: true, message: "请填写盗版网站网址", trigger: 'blur' },
						{ validator: validateUrl, trigger: 'blur' }
					],
					unauth_name: [{ required: true, message: "请填写盗版内容名称" }],
					pic: [{ required: true, message: "请上传盗版网站截图" }],
				},
				fileList: {
					unauth: [],
				},
				// 上传地址
				uploadUrl: submitfile,
				requires_id: null,
				unauth_id: null,
			}
		},
		mounted() {
			this.getTableData();
		},
		computed: {
			...mapState([
				'crocUser',
			]),
		},
		methods: {
			...mapMutations([
				'OUT_LOGIN',
			]),
			
			// 盗版截图上传：
			unauthRemove(file, fileList) {
				// if(this.unauth_pic_length==0) return;
				// this.unauth_pic_length--
				this.formAdd.pic = '';
			},
			unauthSuccess(res, file) {
				// this.unauth_pic_length++
				this.formAdd.pic = res.data;
			},
			unauthUpload(file) {
				const isJPG = file.type === 'image/jpeg' || file.type === 'image/png' || file.type === 'image/gif' || file.type === 'image/bmp';
				const isLt2M = file.size / 1024 / 1024 < 2;
				if (!isJPG) {
					this.$message.error('上传封面图片只能是 JPEG/BMP/PNG/GIF 格式!');
				}
				if (!isLt2M) {
					this.$message.error('上传封面图片大小不能超过 2MB!');
				}
				return isLt2M;
			},
			unauthExceed(files, fileList) {
				this.$message.warning(`最多上传1个文件`);
			},
			// 判断是否为IP地址
			isIp(value){
				let regexp = /^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$/;

				let valid = regexp.test(value);
		
				if(!valid){//首先必须是 xxx.xxx.xxx.xxx 类型的数字，如果不是，返回false
					return false;
				}
				
				return value.split('.').every(function(num){
					//切割开来，每个都做对比，可以为0，可以小于等于255，但是不可以0开头的俩位数
					//只要有一个不符合就返回false
					if(num.length > 1 && num.charAt(0) === '0'){
						//大于1位的，开头都不可以是‘0’
						return false;
					}else if(parseInt(num , 10) > 255){
						//大于255的不能通过
						return false;
					}
					return true;
				});
			},
			// 添加删除链接
			IsURL(str_url) {            	
				return !!str_url.match(/^(http|https):\/\/[\w\-_]+(\.[\w\-_]+)+([\w\-\.,@?^=%&:/~\+#]*[\w\-\@?^=%&/~\+#])?/);
			},
			// 验证授权网址
			validateAuthUrl: function(rule, value, callback){
				if (value === '') {
					callback();
				} else {
					let domainArr = value.match(/[\w-]+\.(com|net|org|gov|cc|biz|info|cn|co|mobi|name|sh|ac|la|travel|tm|us|cc|tv|jobs|asia|hn|lc|hk|bz|ws|tel|io|tw|is|edu|mil|au|jp|int|kr|de|vc|ag|in|me|gd|vg|be|sg|it|ro|pw|win|cm|im|ca|top|wang|tt|so|xyz|vip|tn)\b(\.(cn|hk|uk|jp|tw|kr|mo|kr|ru))*/);
					// 2017-11-14 18:00:31 liuzz
					if(!domainArr){
						let urlReg = /[a-zA-Z0-9][-a-zA-Z0-9]{0,62}(\.[a-zA-Z0-9][-a-zA-Z0-9]{0,62})+\.?/;  
						let urlIP=urlReg.exec(value);
						if(urlIP){
							if(this.isIp(urlIP[0])){
								domainArr = true;
							}
						}
					}
					if(!this.IsURL(value) || !domainArr){
						callback(new Error('此网址不是以http://https://开头，或者不是网址'));
					}else{
						callback();
					}
				}
			},
			// 翻页 
			handleCurrentChange(val) {
				this.page = val;
				this.getTableData();
			},
			getTableData(){
				this.listLoading = true;
				let para = {
					uid: this.crocUser.uid,
					name: this.filters.name,
					page: this.page,
					pagesize: 10,
				};

				getunauthrequires(para).then(res => {
					this.listLoading = false;
					if (res.data) {
						this.total = res.total;
						this.tableData = res.data;
					}else if(res.tologin) {
						this.OUT_LOGIN();
						this.$router.push('/login');
					}else {
						this.$message.error(res.msg);
					}
				});
			},

			// 显示添加
			handleAdd(index,row){
				this.requires_id = row.requires_id;
            	// this.unauth_id = null;
				this.formAdd.requires_id = row.requires_id;
				this.formAddVisible = true;
			},

			// 提交添加
			submitAdd(formName){
				this.$refs[formName].validate((valid) => {
					if (valid) {
						const loading = this.$loading({
							lock: true,
							text: '正在上传',
							spinner: 'el-icon-loading',
							background: 'rgba(0, 0, 0, 0.7)'
						});

						// 图片上传
						let _this = this;
						let timer1= setInterval(()=>{
							if(_this.formAdd.pic != ''){
								// 清除定时器
								clearInterval(timer1); 
								clearTimeout(timer2);
								timer1 = null; 
								timer2 = null;

								async function submit() {
									let para = Object.assign({}, _this.formAdd);
									para.uid = _this.crocUser.uid;
									let res_add  = await unauthAdd(para);
									if(res_add.data){
										_this.$message.success(res_add.msg);
										_this.$refs[formName].resetFields();
										_this.formAdd.pic = '';
										_this.fileList = {
											unauth: [] // 样本
										};
										_this.formAddVisible = false;
										_this.getTableData();
									}else if(res_add.tologin) {
										_this.OUT_LOGIN();
										_this.$router.push('/login');
									}else {
										_this.$message.error(res_add.msg);
									}

									loading.close();
								}
								submit();
							}
						},30);
						// 请求超时
						let timer2 = setTimeout(()=>{
							// 清除定时器
							clearInterval(timer1); 
							clearTimeout(timer2);
							timer1 = null; 
							timer2 = null;
							this.$message('请求超时，请重试');
							loading.close();
						},5000);
					
						// let para = Object.assign({},this.formAdd);
						// para.uid = this.crocUser.uid,
						// userAdd(para).then(res => {
						// 	if(res.data){
						// 		this.$message.success(res.msg);
						// 		this.resetForm(formName);
						// 		this.formAddVisible = false;
						// 		this.getTableData();
						// 	}else if(res.tologin) {
						// 		this.OUT_LOGIN();
						// 		this.$router.push('/login');
						// 	}else {
						// 		this.$message.error(res.msg);
						// 	}
						// })

					} else {
						console.log('error submit!!');
						return false;
					}
				});
			},
			// 重置 
			resetForm(formName){
				this.$refs[formName].resetFields();
			},
		}
	}

</script>

<style scoped lang="scss">

// 上传组件
.el-form-pic .el-form-item__content{
	line-height: normal;
	.el-upload--picture-card{
		width: 100px;
		height: 100px;
		line-height: 100px;
	}
	.el-upload-list--picture-card{
		display: inline-block;
		height: 100px;
	}
	.el-upload-list--picture-card .el-upload-list__item{
		width: 100px;
		height: 100px;
	}

	.el-upload-list--picture-card .el-progress {
		width: 80px;
	}
	.el-upload-list--picture-card .el-progress-circle {
		width: 80px!important;
		height: 80px!important;
	}
	// 取消上传图片默认效果
	.el-upload-list__item {
		transition: none!important;
		-webkit-transition: none!important;
	}
}

</style>